#include <iostream>
#include <vector>
#include <set>
using namespace std;

struct link{
	int Address,Data,Next;
};
struct rule{
	bool operator()(link a1,link a2){
		return a1.Address<a2.Address;
	}
};

int main(){
	int f,N,K;
	cin>>f>>N>>K;
	link l;
	vector <link> v,vF,vS,vT;
	set <link,rule> s;
	for( int i=0; i<N; i++ ){
		cin>>l.Address>>l.Data>>l.Next;
		s.insert(l);
	}
	set <link,rule> ::iterator q; 
	l.Address=f;
	while( l.Address!=-1 ){
		q=s.find(l);
		v.push_back(*q);
		l.Address=q->Next;
	}
	for( int i=0; i<v.size(); i++ ){
		if( v[i].Data<0 ){
			vF.push_back(v[i]);
		}else if( v[i].Data>K ){
			vT.push_back(v[i]);
		}else{
			vS.push_back(v[i]);
		} 
	}
	int flag=0;
	vector <link>::iterator p;
/*	if( vF.size()!=0 ) printf("%05d %d ",vF[0].Address,vF[0].Data);flag=1;
	for( int i=1; i<vF.size(); i++ )	printf("%05d\n%05d %d ",vF[i].Address,vF[i].Address,vF[i].Data);flag=1;
	if( flag==0&&vS.size()!=0 ) printf("%05d %d ",vF[0].Address,vF[0].Data);flag=1;
	for( int i=0; i<vS.size(); i++ )	printf("%05d\n%05d %d ",vS[i].Address,vS[i].Address,vS[i].Data);flag=1;
	if( flag==0&&vT.size()!=0 ) printf("%05d %d ",vF[0].Address,vF[0].Data);flag=1;
	for( int i=0; i<vT.size(); i++ )	printf("%05d\n%05d %d ",vT[i].Address,vT[i].Address,vT[i].Data);flag=1;
*/	
	for( p=vF.begin(); p!=vF.end(); p++ ){
		if( flag==0 ){
			printf("%05d %d ",p->Address,p->Data);flag=1;
		}else{
			printf("%05d\n%05d %d ",p->Address,p->Address,p->Data);flag=1;
		}
	}
	for( p=vS.begin(); p!=vS.end(); p++ ){
		if( flag==0 ){
			printf("%05d %d ",p->Address,p->Data);flag=1;
		}else{
			printf("%05d\n%05d %d ",p->Address,p->Address,p->Data);flag=1;
		}
	}
	for( p=vT.begin(); p!=vT.end(); p++ ){
		if( flag==0 ){
			printf("%05d %d ",p->Address,p->Data);flag=1;
		}else{
			printf("%05d\n%05d %d ",p->Address,p->Address,p->Data);flag=1;
		}		
	}
	printf("-1");
	return 0;
}
